#include "../import/head.h"
#include "http_proc.h"
#include "../import/import.h"
#include "../data_struct/head.h"
#include "../global/head.h"
#include "../macro/head.h"
#include "../msg/head.h"

////////////////////////////////////////////////////////////////////////////////////////////
// 

namespace xos_sgsj
{

	//////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 

	http_proc::http_proc()
	{
	}

	http_proc::~http_proc()
	{
	}

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// proc

	int http_proc::proc( session * pSession )
	{
		int ret = 0;

		tcp * pTcp = pSession->m_pTcp;
		const char * lpszPath = 0;
		xos::i_buf * pBuf = 0;

		if( 0 == ret )
		{
			ret = g_pSysData->m_os.m_pXos->create( xos::i_xos::XOS_OBJ_BUF, (void **)&pBuf );
		}

		if( ( 0 == ret ) && ( 0 != pTcp->m_pParseRequest->query_path( 0, &lpszPath, true ) ) )
		{
			char buf[] = "no info recved";
			int len = g_pSysData->m_os.m_pCrt->strlen( buf );
			pBuf->set_data( buf, len );
			ret = 1;
		}

		if( 0 == ret )
		{
			if( 0 == g_pSysData->m_os.m_pCrt->stricmp( lpszPath, HTTP_QUIT_PROGRAM ) )
			{
				ret = proc_quit( pSession, pBuf );
			}
			else
			{
				ret = proc_unknown( lpszPath, pSession, pBuf );
			}
		}

		if( pBuf )
		{
			pTcp->m_pComposeRet->set_ret_code( "200 OK" );
			pTcp->m_pComposeRet->set_tag( "Server", "ghh test" );
			pTcp->m_pComposeRet->set_body_len( pBuf->get_len( 0 ) );
			pSession->add_ref( 1 );
			pTcp->m_pComposeRet->compose( pBuf );
			pBuf = 0;
		}

		if( pBuf )
		{
			pBuf->release();
			pBuf = 0;
		}

		return ret;
	}

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 

	int http_proc::proc_quit( session * pSession, xos::i_buf * pBuf )
	{
		int ret = 0;

		pBuf->set_data( "quit ok", 7 );

		data * p = g_pSysData->m_pPool->m_data_pool.GetItem();
		p->init();
		p->m_nMsg = MSG_QUITING;
		g_pSysData->m_pImpl->notify( p );
		p = 0;

		return ret;
	}

	int http_proc::proc_unknown( const char * lpszPath, session * pSession, xos::i_buf * pBuf )
	{
		int ret = 0;

		char * lpszData = pBuf->get_data( 0, 0, 0 );
		int nHasRet = 0;

		if( 0 == ret )
		{
			lpszData[0] = 0;
		}

		while( ( 0 == ret ) && ( 0 == nHasRet ) && lpszPath )
		{
			g_pSysData->m_os.m_pMisc->url_append( lpszData, lpszPath );
			nHasRet = pSession->m_pTcp->m_pParseRequest->query_path( 0, &lpszPath, false );
		}

		if( 0 == ret )
		{
			int len = g_pSysData->m_os.m_pCrt->strlen( lpszData );
			pBuf->set_len( len );
		}

		return ret;
	}

} // xos_sgsj
